import Taro from '@tarojs/taro';
import { create } from 'zustand';
import { immer } from 'zustand/middleware/immer';
import { getUserHome } from '@/business/services/user/userInfo';
import { cancelOperateDemand, operateCancelCollect, operateCollect, operateDemand } from '@/business/services/demand/demand';
import { demandListStore, RequestFunction2, RequestFunction3 } from '../demand/demandList';

/**
 * @description 个人空间
 * @author Shawn
 */

type RequestFunction = (userId: string) => Promise<void>;

type State = {
  // 个人空间信息
  userDetail: any;
  // 数据是否加载完成
  isDataLoaded: boolean;
};

type Actions = {
  // 获取个人空间信息
  getUserInfo: RequestFunction;
  // 点赞、点踩
  handleLikeOrDislike: RequestFunction2;
  // 取消点赞、点踩
  handleCancelLikeOrDislike: RequestFunction2;
  // 收藏
  handleCollect: RequestFunction2;
  // 取消收藏
  handleCancelCollect: RequestFunction3;
  // 清空个人空间信息
  clearUserInfo: () => void;
};

const initialState: State = {
  // 个人空间信息
  userDetail: {},
  // 数据是否加载完成
  isDataLoaded: true,
};

export const userDetailStore = create<State & Actions>()(
  immer((set, get) => ({
    ...initialState,

    /**
     * 获取个人空间信息
     * @param userId 用户id
     */
    getUserInfo: async (userId: string) => {
      set((state) => {
        state.isDataLoaded = true;
      });
      try {
        Taro.showLoading({
          title: '加载中',
        });
        const requestData = {
          userId: userId,
        };
        const result = await getUserHome(requestData);
        console.log('获取个人空间信息result===', result);
        if (result.success) {
          set((state) => {
            state.userDetail = result.data ? result.data : {};
          });
        }
      } catch (error) {
        console.log(error);
      } finally {
        Taro.hideLoading();
        set((state) => {
          state.isDataLoaded = false;
        });
      }
    },

    /**
     * 点赞、点踩
     * @param demandId 需求id
     * @param type 操作类型，LIKE-点赞，DISLIKE-点踩
     */
    handleLikeOrDislike: async (demandId: string, type: string, status: string, tag: string) => {
      try {
        console.log('handleLikeOrDislike111')
        const result = await operateDemand({ demandId, type, status });
        if (result.success) {
          set((state) => {
            const item = state.userDetail?.ownDemands.find((d) => d.id === demandId);
            const item1 = state.userDetail?.needDemands.find((d) => d.id === demandId);
            if (item) {
              if (type === 'LIKE') {
                // 如果之前点踩了，先取消点踩
                if (item.isDisliked) {
                  item.dislikeCount = (item.dislikeCount || 0) - 1;
                  item.isDisliked = false;
                }
                item.likeCount = (item.likeCount || 0) + 1;
                item.isLiked = true;
              } else {
                // 如果之前点赞了，先取消点赞
                if (item.isLiked) {
                  item.likeCount = (item.likeCount || 0) - 1;
                  item.isLiked = false;
                }
                item.dislikeCount = (item.dislikeCount || 0) + 1;
                item.likeCount = (item.likeCount || 0) - (item.isLiked ? 1 : 0);
                item.isLiked = false;
                item.isDisliked = true;
              }
            }

            if (item1) {
              if (type === 'LIKE') {
                // 如果之前点踩了，先取消点踩
                if (item1.isDisliked) {
                  item1.dislikeCount = (item1.dislikeCount || 0) - 1;
                  item1.isDisliked = false;
                }
                item1.likeCount = (item1.likeCount || 0) + 1;
                item1.isLiked = true;
              } else {
                // 如果之前点赞了，先取消点赞
                if (item1.isLiked) {
                  item1.likeCount = (item1.likeCount || 0) - 1;
                  item1.isLiked = false;
                }
                item1.dislikeCount = (item1.dislikeCount || 0) + 1;
                item1.likeCount = (item1.likeCount || 0) - (item1.isLiked ? 1 : 0);
                item1.isLiked = false;
                item1.isDisliked = true;
              }
            }
            
          });
          // 更新demandList中的对应项
        demandListStore.setState((listState) => {
          const index = listState.demandList.findIndex((item) => item.id === demandId);
          if (index !== -1) {
            const item = listState.demandList[index];
            if (type === 'LIKE') {
              if (item.isDisliked) {
                item.dislikeCount = (item.dislikeCount || 0) - 1;
                item.isDisliked = false;
              }
              item.likeCount = (item.likeCount || 0) + 1;
              item.isLiked = true;
            } else {
              if (item.isLiked) {
                item.likeCount = (item.likeCount || 0) - 1;
                item.isLiked = false;
              }
              item.dislikeCount = (item.dislikeCount || 0) + 1;
              item.likeCount = (item.likeCount || 0) - (item.isLiked ? 1 : 0);
              item.isLiked = false;
              item.isDisliked = true;
            }
          }
        });
        }
        
      } catch (error) {
        console.log(error);
      }
    },

    /**
     * 取消点赞、点踩
     * @param demandId 需求id
     * @param type 操作类型，LIKE-点赞，DISLIKE-点踩
     */
    handleCancelLikeOrDislike: async (demandId: string, type: string) => {
      try {
        const result = await cancelOperateDemand({ demandId });
        if (result.success) {
          set((state) => {
            const item = state.userDetail?.ownDemands.find((d) => d.id === demandId);
            const item1 = state.userDetail?.needDemands.find((d) => d.id === demandId);
            // const item = state.demandDetail;
            if (item) {
              if (type === 'LIKE') {
                item.likeCount = (item.likeCount || 0) - 1;
                item.isLiked = false;
              } else {
                item.dislikeCount = (item.dislikeCount || 0) - 1;
                item.isDisliked = false;
              }
            }
            if (item1) {
              if (type === 'LIKE') {
                item1.likeCount = (item1.likeCount || 0) - 1;
                item1.isLiked = false;
              } else {
                item1.dislikeCount = (item1.dislikeCount || 0) - 1;
                item1.isDisliked = false;
              }
            }
          });
          // 更新demandList中的对应项
          demandListStore.setState((listState) => {
            const index = listState.demandList.findIndex((item) => item.id === demandId);
            if (index !== -1) {
              const item = listState.demandList[index];
              if (type === 'LIKE') {
                item.likeCount = (item.likeCount || 0) - 1;
                item.isLiked = false;
              } else {
                item.dislikeCount = (item.dislikeCount || 0) - 1;
                item.isDisliked = false;
              }
            }
          });
          // // 更新searchList中的对应项
          // searchStore.setState((listState) => {
          //   const index = listState.searchList.findIndex((item) => item.id === demandId);
          //   if (index !== -1) {
          //     const item = listState.searchList[index];
          //     if (type === 'LIKE') {
          //       item.likeCount = (item.likeCount || 0) - 1;
          //       item.isLiked = false;
          //     } else {
          //       item.dislikeCount = (item.dislikeCount || 0) - 1;
          //       item.isDisliked = false;
          //     }
          //   }
          // });
          // // 更新myColletList中的对应项
          // myColletionStore.setState((listState) => {
          //   const index = listState.myColletList.findIndex((item) => item.id === demandId);
          //   if (index !== -1) {
          //     const item = listState.myColletList[index];
          //     if (type === 'LIKE') {
          //       item.likeCount = (item.likeCount || 0) - 1;
          //       item.isLiked = false;
          //     } else {
          //       item.dislikeCount = (item.dislikeCount || 0) - 1;
          //       item.isDisliked = false;
          //     }
          //   }
          // });
        }
      } catch (error) {
        console.log(error);
      }
    },

    /**
     * 收藏
     */
    handleCollect: async (demandId: string, type: string, status: string, tag: string) => {
      try {
        const result = await operateCollect({ demandId, type, status });
          if (result.success) {
            set((state) => {
              const item = state.userDetail?.ownDemands.find((d) => d.id === demandId);
              const item1 = state.userDetail?.needDemands.find((d) => d.id === demandId);
              if (item) {
                if (type === 'COLLECT' || type === 'collection') {
                  item.collectCount = (item.collectCount || 0) + 1;
                  item.collect = true;
                }
              }
              if (item1) {
                if (type === 'COLLECT' || type === 'collection') {
                  item1.collectCount = (item1.collectCount || 0) + 1;
                  item1.collect = true;
                }
              }
            });
          }
      } catch (error) {
        console.log(error);
      }
    },

    /**
     * 取消收藏
     */
    handleCancelCollect: async (demandId: string, tag: string) => {
      try {
        const result = await operateCancelCollect({ demandId });
          if (result.success) {
            set((state) => {
              const item = state.userDetail?.ownDemands.find((d) => d.id === demandId);
              const item1 = state.userDetail?.needDemands.find((d) => d.id === demandId);
              if (item) {
                item.collectCount = (item.collectCount || 0) - 1;
                item.collect = false;
                console.log('handleCancelCollect success');
              }
              if (item1) {
                item1.collectCount = (item1.collectCount || 0) - 1;
                item1.collect = false;
                console.log('handleCancelCollect success');
              }
            });
          }
        
      } catch (error) {
        console.log(error);
      }
    },

    /**
     * 清空个人空间信息
     */
    clearUserInfo: () => {
      set((state) => {
        state.userDetail = {};
      });
    },
  })),
);
